# -*- coding:utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import get_object_or_404
from wenlincms import template
from wenlincms.utils.models import get_user_model

from wlapps.article.models import ArticlePost, ArticleCategory

User = get_user_model()
register = template.Library()


@register.as_tag
def article_categories(*args):
    posts = ArticlePost.objects.published()
    categories = ArticleCategory.objects.filter(articleposts__in=posts).order_by("id")
    return list(categories.annotate())


# 获取分类下最近发布的10篇文章
@register.as_tag
def category_articles(v):
    posts = ArticlePost.objects.published()
    category = get_object_or_404(ArticleCategory, slug=v)
    return posts.filter(categories=category).order_by("-created")[:10]
